﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Sisocana.Core.Models;
using Sisocana.Core.Interfaces;
using Sisocana.Core;
using SisocanaFronEnd.Models;
using System.IO;
using System.ServiceModel.Syndication;

namespace SisocanaFronEnd.Controllers
{
    public class PersonController : SiteController
    {
        #region Contructor/Variables

        private IPersonaService _personaProvider;

        public PersonController() : this(new PersonaService())
        {
        }

        public PersonController(IPersonaService provider)
        {
            _personaProvider = provider ?? new PersonaService();
        }

        #endregion

        public void Image(int id)
        {
            DataImagen imagen = _personaProvider.GetPhoto(id);
            if (imagen.imgByte != null)
            {
                Response.ContentType = imagen.imgExt;
                Response.BinaryWrite(imagen.imgByte);
            }
        }

        public void imageExt(DataImagen foto)
        {
            if ((foto.imgByte != null)&&(foto.imgExt!=null))
            {
                Response.ContentType = foto.imgExt;
                Response.BinaryWrite(foto.imgByte);
            }
        }


        public ActionResult Report()
        {
            return View();            
        }
        
        [HttpPost]
        public ActionResult Report(ReportMissingPersonViewModel model, string create)
        {
            if(!ModelState.IsValid)
                return View();
            if (create != "Create a new record")
            {
                IList<PersonaDesaparecidaFullModel> personas = _personaProvider.GetSimilar(ViewBag.Site.id,model.nombre, model.apellido);
                if (personas.Count != 0)
                {
                    model.personas = personas;
                    return View(model);
                }
            }
            return View("MissingPerson", new MissingPersonViewModel(model.nombre, model.apellido));
        }

        [HttpPost]
        public ActionResult MissingPerson(MissingPersonViewModel editedMissingPerson, HttpPostedFileBase photo)
        {
            if (ModelState.IsValid)
                try
                {
                    var imagen = new DataImagen();
                    if (photo != null && photo.ContentLength > 0)
                    {
                        imagen.imgByte = new byte[photo.ContentLength];
                        photo.InputStream.Read(imagen.imgByte, 0, imagen.imgByte.Length);
                        imagen.imgExt = Path.GetExtension(photo.FileName);
                        imagen.imgNombre = photo.FileName;
                    }
                    editedMissingPerson.Persona.foto = imagen;
                    editedMissingPerson.Persona.idSitio = ViewBag.Site.id;
                    int newPersonId = _personaProvider.crearRegistroPersonaDesaparecida(editedMissingPerson.Persona, editedMissingPerson.HomeAddress, editedMissingPerson.Reporte);
                    return View("Success", new MessageModel("Report missing person", "We appreciate your contribution", "The report was succesfully saved"));
                }
                catch (Exception e)
                {
                    return View("SiteError", new MessageModel("Report missing person", "An unexpected error has occurred", e.Message));
                }
            return View(editedMissingPerson);
        }

        public ActionResult FoundPerson(int id, bool externalEntity, int searchWSId, int idSitio, string name, string lastName, DateTime date, string phone)
        {
            return View(new FoundPersonViewModel(ViewBag.Site.id,id,externalEntity, searchWSId,idSitio,name,lastName,date,phone));
        }

        [HttpPost]
        public ActionResult FoundPerson(FoundPersonViewModel model)
        {
            if (ModelState.IsValid)
                try
                {
                    if (model.Reporte.idPersona > 0)
                    {
                        int result = _personaProvider.agregarReportePersonaDesaparecida(ViewBag.Site.id, model.Reporte);
                        if(result==0)
                            return View("Success", new MessageModel("Make a report", "We appreciate your contribution", "The report was succesfully saved"));
                        else
                            return View("SiteError", new MessageModel("Make a report", "An unexpected error has occurred.", "The service may be unavailable or not supported by an external site."));
                    }
                    else
                    {
                        return RedirectToAction("Report");
                    }
                }
                catch (Exception e)
                {
                    return View("SiteError", new MessageModel("Make a report", "An unexpected error has occurred.", e.Message));
                }
            return View(model);
        }

        public ActionResult HelpRequests()
        {
            int idSitio = ViewBag.Site.id;
            try
            {
               return View(_personaProvider.GetAllPersonaAyudaModel(idSitio));
            }
            catch
            {
                return View("SiteError", new MessageModel("Make a report", "We're really sorry!", "The help request you're looking for doesn't exist"));
            }
        }

        public JsonResult JsonHelpRequest(int id)
        {
            try
            {
                int idSitio = ViewBag.Site.id;
                PersonaAyudaModel helpRequest = _personaProvider.LatestHelpRequests(idSitio, id);
                if(helpRequest == null)
                    return Json(new { isNew = false });
                else
                    return Json(new { isNew = true,
                                        id = helpRequest.id,
                                        html = RenderPartialViewToString("AjaxHelpRequest", helpRequest)
                                    });
            }
            catch
            {
                return Json(new { isNew = false });
            }
        }

        public ActionResult HelpRequest(int id)
        {
            try
            {
                return View(_personaProvider.GetPersonaAyudaModel(id));
            }
            catch
            {
                return View("SiteError", new MessageModel("Make a report", "We're really sorry!", "The help request you're looking for doesn't exist"));
            }
        }

        public ActionResult MakeHelpRequest()
        {
            return View();
        }

        [HttpPost]
        public ActionResult MakeHelpRequest(PersonaAyudaModel persona, HttpPostedFileBase photo)
        {
            if (ModelState.IsValid)
                try
                {
                    var imagen = new DataImagen();
                    if (photo != null && photo.ContentLength > 0)
                    {
                        imagen.imgByte = new byte[photo.ContentLength];
                        photo.InputStream.Read(imagen.imgByte, 0, imagen.imgByte.Length);
                        imagen.imgExt = Path.GetExtension(photo.FileName);
                        imagen.imgNombre = photo.FileName;
                    }
                    persona.foto = imagen;
                    persona.idSitio = ViewBag.Site.id;
                    int newHelpRequestId = _personaProvider.makeHelpRequest(persona);
                    return View("Success", new MessageModel("Make a help request", "Help is on the way!", "The request was succesfully saved"));
                }
                catch (Exception e)
                {
                    return View("SiteError", new MessageModel("Make a help request", "An unexpected error has occurred", e.Message));
                }
            return View(persona);
        }
        
        public ActionResult Rss()
        {
            // Leo el host a ver de que sitio hizo el pedido
            string prot = "http";
            string host = HttpContext.Request.Url.Authority;
            string hostSolo  = host.Split('.')[0];
            ISiteService siteService = new SiteService();
            SiteModel sitio = siteService.GetSingle(s => s.subdominio.Trim() == hostSolo);
            if (sitio == null)
            {
                SyndicationFeed feedv = new SyndicationFeed();
                return new RssResult(feedv);
            }
            int idSitio = sitio.id;

            List<SyndicationItem> items = new List<SyndicationItem>();
            SyndicationItem item;

            var pedidos = _personaProvider.GetAllPersonaAyudaModel(idSitio);

            string fotoUrl = String.Format("{0}://{1}{2}/{3}/{4}", prot, host, HttpRuntime.AppDomainAppVirtualPath, "Util", "imagenT");

            foreach (PersonaAyudaModel p in pedidos) {
                
                               
                item = new SyndicationItem();
                item.Title = new TextSyndicationContent(p.nombre +" "+  p.apellido + "is asking for help.");
                /*Aca faltaria armar la url par ir a ver le pedidode ayuda*/
                SyndicationLink link = new SyndicationLink(new Uri("http://www.armarlaurl.com"));
                item.Links.Add(link);

                string fotoUrlItem = fotoUrl+"/"+p.id.ToString();
                string sum = "<p><img src=\"" + fotoUrlItem + "\"  align=\"left\" style=\"vertical-align: middle;\"> The situation described was: \"" +
                p.descripcionSituacion.Trim() + "\"</p>"; 


                item.Summary = new TextSyndicationContent(sum);
                item.Authors.Add(new SyndicationPerson("", p.nombre, ""));

                string htmlCont = "<h1> contenido </h1>";

                item.Content = SyndicationContent.CreateHtmlContent(htmlCont);
                item.PublishDate = p.fecha;
                items.Add(item);                                    
            }

            SyndicationFeed feed = new SyndicationFeed("Ask for Help " + sitio.nombreCatastrofe + " Rss", "Ask for Help " + sitio.nombreCatastrofe + " Rss", Request.Url, items);

            string imgurl = String.Format("{0}://{1}{2}/{3}/{4}/{5}", prot, host, HttpRuntime.AppDomainAppVirtualPath, "Recursos", "imagen", idSitio);   
            feed.ImageUrl = new Uri(imgurl);
            return new RssResult(feed);
        }

    }
}
